// 上传文件
function upload_file_server(url, that, upload_picture_list, j, PED) {
  const upload_task = wx.uploadFile({
    url,
    filePath: upload_picture_list[j]['path'],
    name: 'file',
    formData: {
      'num': PED
    },
    success(res) {
      // let data = JSON.parse(res.data);
      // let filename = data[0].url
      upload_picture_list[j]['path_server'] = upload_picture_list[j]['path']
      that.setData({
        upload_picture_list: upload_picture_list
      });
      wx.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 2000
      })
    }
  })
  upload_task.onProgressUpdate((res) => {
    upload_picture_list[j]['upload_percent'] = res.progress
    that.setData({
      upload_picture_list: upload_picture_list
    });
  });
}


// 上传图片(this,api.imageup)
function uImage(_that, url, PED) {
  for (let j in _that.data.upload_picture_list) {
    if (_that.data.upload_picture_list[j]['upload_percent'] == 0) {
      upload_file_server(url, _that, _that.data.upload_picture_list, j, PED)
    }
  }
}


// 删除图片
function dImage(e, _that) {
  _that.data.upload_picture_list.splice(e.currentTarget.dataset.index, 1);
  _that.setData({
    upload_picture_list: _that.data.upload_picture_list
  });
}


// 选择图片
function cImage(_that, count) {
  wx.chooseImage({
    count,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: function(res) {
      _that.data.imgs = res.tempFilePaths;
      for (let i in res.tempFiles) {
        res.tempFiles[i]['upload_percent'] = 0
        res.tempFiles[i]['path_server'] = ''
        _that.data.upload_picture_list.push(res.tempFiles[i])
      }
      _that.setData({
        upload_picture_list: _that.data.upload_picture_list,
      });
    }
  })
}

// 预览图片
function pImage(e, _that) {
  wx.previewImage({
    current: _that.data.imgs[e.currentTarget.dataset.index],
    urls: _that.data.imgs
  })
}


module.exports = {
  upload_file_server,
  uImage,
  dImage,
  cImage,
  pImage
}